package com.own.business.question.business.util;

import com.own.business.question.entity.po.Question;
import com.own.business.question.entity.vo.QuestionOptionVo;
import com.own.business.question.entity.vo.QuestionVo;
import lombok.NonNull;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * QuestionUtil
 *
 * @author chenxueli
 * @date 2021/5/14 9:47
 */
public class QuestionUtil {

    /**
     * 清除答案信息
     */
    public static void clearAnswer(@NonNull QuestionVo question) {
        if (question.getOptionList() != null && question.getOptionList().size() > 0) {
            question.getOptionList().parallelStream().forEach(QuestionUtil::clearAnswer);
        }
        question.setWeight(null);
        question.setDisabled(null);
        question.setAnswer(null);
        question.setExplainSimple(null);
        question.setExplainDetail(null);
    }

    /**
     * 打乱选项（一定要在清除答案信息之前）
     */
    public static void shuffle(@NonNull QuestionVo question) {
        shuffle(question, null);
    }

    /**
     * 打乱选项（一定要在清除答案信息之前）
     *
     * @param sortList 顺序
     */
    public static void shuffle(@NonNull QuestionVo question, List<Integer> sortList) {
        if (question.getType().equals(Question.Type.SINGLE_CHOICE) || question.getType().equals(Question.Type.MULTIPLE_CHOICE)) {
            // 只有打乱顺序的方式不一样
            if (sortList == null) {
                Collections.shuffle(question.getOptionList());
            } else {
                var optionMap = question.getOptionList().stream().collect(Collectors.toMap(QuestionOptionVo::getSortOrder, option -> option));
                var optionList = sortList.stream().map(optionMap::get).filter(Objects::nonNull).collect(Collectors.toList());
                question.setOptionList(optionList);
            }
            var answerList = new ArrayList<String>();
            var keyList = new ArrayList<String>();
            var length = question.getOptionList().size();
            for (int i = 0; i < length; i++) {
                var option = question.getOptionList().get(i);
                keyList.add(option.getSortOrder() + "");
                if (option.getIsAnswer() != null && option.getIsAnswer() == 1) {
                    answerList.add(String.valueOf((char) (65 + i)));
                }
            }
            question.setAnswer(String.join(",", answerList));
            question.setKeySortOrder(String.join(",", keyList));
        }
    }

    /**
     * 清除答案信息
     */
    public static void clearAnswer(@NonNull QuestionOptionVo option) {
        option.setIsAnswer(null);
        option.setSortOrder(null);
    }

}
